﻿using System.Reflection;
using ECommon.Components;
using ECommon.Configurations;
using ECommon.Logging;
using ECommon.Serilog;
using ENode.Configurations;
using ENode.Infrastructure;
using ENode.MySQL;
using ESTAR.Domain.Auth;
using ESTAR.Infrastructure;
using Microsoft.Extensions.Configuration;

namespace ESTAR.CommandService
{
    public class Bootstrap
    {
        private static ENodeConfiguration _enodeConfiguration;


        public static void Initialize(IConfiguration config)
        {
            InitializeENode(config);
            InitializeCommandService();
        }
        public static void Start()
        {
            _enodeConfiguration.StartEQueue().Start();
        }
        public static void Stop()
        {
            _enodeConfiguration.ShutdownEQueue().Stop();
        }

        private static void InitializeENode(IConfiguration config)
        {
            ConfigSettings.Initialize(config);

            var assemblies = new[]
            {
                Assembly.Load("ESTAR.Infrastructure"),
                Assembly.Load("ESTAR.Commands"),
                Assembly.Load("ESTAR.Domain"),
                Assembly.Load("ESTAR.Domain.Dapper"),
                Assembly.Load("ESTAR.CommandHandlers"),
                Assembly.Load("ESTAR.CommandService")
            };
    

            _enodeConfiguration = ECommon.Configurations.Configuration
                .Create()
                .UseAutofac()
                .RegisterCommonComponents()
                .UseSerilog()
                .UseJsonNet()
                .RegisterUnhandledExceptionHandler()
                .CreateENode()
                .RegisterENodeComponents()
                .RegisterBusinessComponents(assemblies)
                .UseMySqlEventStore()
                .UseMySqlLockService()
                .UseEQueue()
                .BuildContainer()
                .InitializeMySqlEventStore(ConfigSettings.ENodeConnectionString)
                .InitializeMySqlLockService(ConfigSettings.ENodeConnectionString)
                .InitializeBusinessAssemblies(assemblies);
        }
        private static void InitializeCommandService()
        {
            ObjectContainer.Resolve<ILockService>().AddLockKey(typeof(UserInfo).Name);
            var log = ObjectContainer.Resolve<ILoggerFactory>();
            ObjectContainer.Resolve<ILoggerFactory>().Create(typeof(Program)).Info("Command service initialized.");
        }
    }
}
